#!/usr/bin/perl

use CGI qw(:standard);
use DBI;
use strict;

my $in=CGI->new;

my %input=$in->Vars;

# debugging
#$input{'name'}='1934-638';

print $in->header('text/json');

my @planetnames=('mercury','venus','mars','jupiter',
		 'saturn','uranus','neptune','sun');
my @months=('JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG',
	    'SEP','OCT','NOV','DEC');

# Changeable program locations.
# The Miriad task 'planets'.
#my $planets="/nfs/atapplic/miriad/linux/bin/planets";
my $planets = "/home/jstevens/usr/src/miriad/linux64/bin/planets";
# The location of wget.
#my $wget="/usr/X11R6/bin/wget";
my $wget = "/usr/bin/wget";

print "{";

if (!$input{'name'}){
    print " error: 'No name supplied.', name: '', position: {} }\n";
    exit;
}

if (!$input{'noplanets'}) {
    # check for a planet first
    my $cn=lc($input{'name'});
    for (my $i=0;$i<=$#planetnames;$i++){
	if ($planetnames[$i] eq $cn){
	    my @time=gmtime;
	    my $epoch=sprintf "%4d%3s%02dT%02d:%02d:%02d",
	    $time[5]+1900,$months[$time[4]],$time[3],
	    $time[2],$time[1],$time[0];
	    my $info=`$planets source=$planetnames[$i] epoch=$epoch`;
	    my @infosplit=split(/\n/,$info);
	    my ($ra,$dec);
	    for (my $j=0;$j<=$#infosplit;$j++){
		if ($infosplit[$j]=~/RA:\s+(.*)$/){
		    $ra=$1;
		} elsif ($infosplit[$j]=~/DEC:\s+(.*)$/){
		    $dec=$1;
		}
	    }
	    print "name: '".$input{'name'}."', position: {".
		"ra: '".$ra."', dec: '".$dec."', epoch: 'J2000' }, ".
		"resolver: 'planets' }\n";
	    exit;
	}
    }
}

# the database handle
my $dbh;
# Disable ATCA db on this host.
#$input{'noatcadb'} = 1;

if (!$input{'noatcadb'}) {
    # check first for a name from the calibrator database
    
    &start_database_connection;
    
    my $calquery="SELECT name,ra,dec FROM calibrators WHERE ".
	"contains_text(name,'".$input{'name'}."')=TRUE ORDER BY ".
	"name";
    my $calquery_handle=$dbh->prepare($calquery);
    $calquery_handle->execute;
    if ($calquery_handle->rows>0){
	my @calquery_response=$calquery_handle->fetchrow();
	print " name: '".$input{'name'}."',".
	    "position: { ra: '".$calquery_response[1]."',".
	    "dec: '".$calquery_response[2]."', epoch: 'J2000' },".
	    "resolver: 'atcadb',".
	    " resolvedName: '".$calquery_response[0]."' }\n";
	$calquery_handle->finish;
	$dbh->disconnect;
	exit;
    }
    $calquery_handle->finish;
    $dbh->disconnect;
}

if (!$input{'nosesame'}) {
    # otherwise we query the Sesame database
    my $url="http://cdsws.u-strasbg.fr/axis/services/Sesame?".
	"method=sesame&type=p&name=".$input{'name'};
    
    my $rv = `$wget -q -O - "$url"`;
    my $name;
    my $position;
    my @re=split(/\n/,$rv);
    my ($ra,$dec);
    for (my $i=0;$i<=$#re;$i++){
	if ($re[$i]=~/^\%J\s/){
	    $position=$re[$i];
	    if ($position=~/^(.*)\=\s(.*)$/){
		$position=$2;
#						$position=~s/\s+/\,/g;
		($ra,$dec)=split(/\s+/,$position);
	    }
	} elsif ($re[$i]=~/^%I.0\s/){
	    $name=$re[$i];
	    $name=~s/%I.0\s+//;
	    $name=~s/NAME\s+//;
	}
    }
    
    print " name: '".$input{'name'}."', position: { ra: '".$ra."',".
	"dec: '".$dec."', epoch: 'J2000' }, resolver: 'sesame',".
	" resolvedName: '".$name."' }\n";
    
    exit;
}

# If we get here, no resolver was able to be used, or no source
# was found with that name.
print " error: 'No source could be found with that name with allowed ".
    "resolving services.', name: '".$input{'name'}."', position: {} }\n";

sub start_database_connection {

    # open a connection to the ATCA calibrator database
    my $dsn="dbi:Pg:dbname=atca;host=mentok;port=5432";
#    my $dsn="dbi:Pg:dbname=atca;host=localhost;port=5433";
    my $db_user="postgres";
    my $db_password="postgres";
    $dbh=DBI->connect($dsn,$db_user,$db_password,
		      {RaiseError => 0, AutoCommit => 1,
		       PrintError => 1});

}
